#include "server.h"
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <sys/types.h>         
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include "package.h"
#include <unistd.h>
#include "../c/call_py.h"
#include <fcntl.h>
#include "service.h"
#include <sqlite3.h>

struct t_args{
    int ckt;
    sqlite3 *ppDb;
};

void *fun(void *arg)
{
    /*int ckt = (int)arg;
    char buffer[BUFF_SIZE];
    struct package p;
    struct python_obj pobj;*/

    struct service args;
    struct t_args *t_arg = (struct t_args*)arg;
    //args.ckt = (int)arg;
    args.ckt = t_arg->ckt;
    args.size = BUFF_SIZE;
    args.ppDb = t_arg->ppDb;
    int ret;

    python_init(&args.pobj);

    while(1){
        while((ret = rcv_package(args.ckt,args.buffer,args.size))){
            if(ret == 1){
                printf("客户端%d断开链接 \n",args.ckt);
                pthread_exit(0);
            }
        }
        unpackage(args.buffer,&args.p);

        switch(args.p.protocol){
        case 0:
                lpr(&args);
                break;
        case 1:
                in_parking(&args);
                break;
        case 2:
                out_parking(&args);
                break;
        case 3:
                is_in(&args);
                break;
        default:
                printf("客户端%d:%d未定义服务\n",args.ckt,args.p.protocol);
    }
    }

    return NULL;
}

int main(void)
{
    struct t_args arg;
    int skt,ckt,len;
    struct sockaddr_in sin,cin;
    pthread_t tid;

    if(sqlite3_open(DATABASE,&arg.ppDb) != SQLITE_OK){
        perror("sqlite3_open");
        exit(-1);
    }

    if((skt = socket(PF_INET,SOCK_STREAM,0)) < 0){
        perror("socket");
        exit(-1);
    }

    sin.sin_family = AF_INET;
    sin.sin_port = htons(PORT);
    sin.sin_addr.s_addr = INADDR_ANY;

    if(bind(skt,(const struct sockaddr*)&sin,sizeof(sin)) < 0){
        perror("bind");
        exit(-1);
    }

    if(listen(skt,NUM) < 0){
        perror("listen");
        exit(-1);
    }
    len = sizeof(cin);
    while(1){
        printf("正在等待客户端连接.........\n");
        if((ckt = accept(skt,(struct sockaddr*)&cin,&len)) < 0){
        perror("accept");
        exit(-1);
    }
        printf("%s上线了...\n",inet_ntoa(cin.sin_addr));
        arg.ckt = ckt;
        pthread_create(&tid,NULL,fun,(void*)&arg);
        pthread_detach(tid);
    }

    sqlite3_close(arg.ppDb);
    close(skt);
    python_destory();
    pthread_exit(0);
}




